package com.moyun.common.interceptor;

import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Alias;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.select.SelectBody;
import net.sf.jsqlparser.statement.select.SetOperationList;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.stereotype.Component;

import java.io.StringReader;
import java.sql.Connection;
import java.util.List;
import java.util.Properties;

/**
 * @ClassName DataPermissionInterceptor
 * @Description https://blog.csdn.net/qq_38225558/article/details/122470094
 * @Author yangboxuan
 * @Date 2022/6/20 23:22
 */
@Slf4j
@AllArgsConstructor
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
@Component
public class DataPermissionInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
        /**
         * 非SELECT操作放行(先判断是不是SELECT操作 不是直接过滤)
         */
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
            return invocation.proceed();
        }
        /**
         * 判断是否有 权限注解 并不是所有的SELECT操作都需 权限过滤. 而且数据权限过滤 是根据 用户来 构建的
         * lg: 用户登录校验(从数据库查询用户信息不需要数据权限),免拦截的查询(没有用户信息,所以做不了数据权限)
         */
        /**
         * 未取到用户则放行
         */
//        if (user==null) {
//            return invocation.proceed();
//        }
        /**
         * 接口没有开启数据权限则放行
         */
//        if (!Boolean.TRUE.equals(DataAuthContext.CONTEXT_HOLDER.get())) {
//            return invocation.proceed();
//        }
        /**
        * BoundSql 对象为: 绑定的sql 即MapperId绑定的sql
        * 文章参考链接: https://juejin.cn/post/6996218774286237704
        */
        BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
        /**
         * 执行的SQL语句(获取到原始sql语句)
         */
        String originalSql = boundSql.getSql();
        /**
        * SQL语句的参数
        */
        Object parameterObject = boundSql.getParameterObject();

        // TODO 这里对执行SQL进行自定义处理...
        String finalSql = this.handleSql(originalSql);
        // System.err.println("数据权限处理过后的SQL: " + finalSql); 这种写法第一次见到
        log.info("数据权限处理过后的SQL: " + finalSql);
        // 装载改写后的sql
        metaObject.setValue("delegate.boundSql.sql", finalSql);
        return invocation.proceed();
    }


    /**
     * 改写SQL
     * {@link com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor}
     *
     * @param originalSql 执行的SQL语句
     * @return 处理后的SQL
     * @author zhengqingya
     * @date 2022/1/13 10:43
     */
    private String handleSql(String originalSql) throws JSQLParserException {
        CCJSqlParserManager parserManager = new CCJSqlParserManager();
        Select select = (Select) parserManager.parse(new StringReader(originalSql));
        SelectBody selectBody = select.getSelectBody();
        if (selectBody instanceof PlainSelect) {
            this.setWhere((PlainSelect) selectBody);
        } else if (selectBody instanceof SetOperationList) {
            SetOperationList setOperationList = (SetOperationList) selectBody;
            List<SelectBody> selectBodyList = setOperationList.getSelects();
            selectBodyList.forEach(s -> this.setWhere((PlainSelect) s));
        }
        return select.toString();
    }

    /**
     * 设置 where 条件  --  使用CCJSqlParser将原SQL进行解析并改写
     *
     * @param plainSelect 查询对象
     * @SneakyThrows(Exception.class) 注解的作用, 整体的代码用 try-catch 包裹, catch 里面 抛出异常,交由上层处理
     */
    @SneakyThrows(Exception.class)
    protected void setWhere(PlainSelect plainSelect) {
        Table fromItem = (Table) plainSelect.getFromItem();
        /**
         * 有别名用别名，无别名用表名，防止字段冲突报错
         */
        Alias fromItemAlias = fromItem.getAlias();
        String mainTableName = fromItemAlias == null ? fromItem.getName() : fromItemAlias.getName();
        /**
         *  构建子查询 -- 数据权限过滤SQL 数据权限的核心 mainTableName + ".create_by in ( 1, 2, 3 )";
         */
//        String dataPermissionSql = mainTableName + ".create_by in ( 1, 2, 3 )";
//        if (plainSelect.getWhere() == null) {
//            plainSelect.setWhere(CCJSqlParserUtil.parseCondExpression(dataPermissionSql));
//        } else {
//            plainSelect.setWhere(new AndExpression(plainSelect.getWhere(), CCJSqlParserUtil.parseCondExpression(dataPermissionSql)));
//        }
    }

    /**
     * 生成拦截对象的代理
     *
     * @param target 目标对象
     * @return 代理对象
     */
    @Override
    public Object plugin(Object target) {
        if (target instanceof StatementHandler) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    /**
     * mybatis配置的属性
     *
     * @param properties mybatis配置的属性
     */
    @Override
    public void setProperties(Properties properties) {

    }

}
